<template>
  <el-form
    class="container-fluid"
    label-width="0px"
    :model="formInline"
    size="default"
  >
    <el-form-item class="row" :style="{ height: '42px' }">
      <el-input
        class="input"
        clearable
        v-model.lazy="formInline.name"
        placeholder="输入题目名或ID搜索"
      ></el-input>
      <div class="input">
        <el-cascader
          placeholder="输入知识点进行搜索"
          v-model="setlabel"
          :style="{ width: '100%' }"
          :options="grouplabel"
          filterable
          :props="{
            checkStrictly: true,
            value: 'ID',
            label: 'name',
            expandTrigger: 'hover',
          }"
          clearable
        />
      </div>
    </el-form-item>
    <el-form-item :style="{ height: '42px' }">
      <el-button-group
        size="default"
        v-if="!isAdmin"
        v-model="formInline.range"
      >
        <el-button
          :type="formInline.range === 'public' ? 'primary' : ''"
          value="public"
          @click="formInline.range = 'public'"
          >公开题目</el-button
        >
        <el-button
          v-if="tenant_id"
          :type="formInline.range === 'accoder' ? 'primary' : ''"
          value="accoder"
          @click="formInline.range = 'accoder'"
          >Accoder</el-button
        >
        <el-button
          v-if="showCF(teamId) || showRemotejudge"
          :type="formInline.range === 'codeforces' ? 'primary' : ''"
          value="codeforces"
          @click="formInline.range = 'codeforces'"
          >RemoteJudge</el-button
        >
        <el-button
          v-if="vip"
          :type="formInline.range === 'match' ? 'primary' : ''"
          value="match"
          @click="formInline.range = 'match'"
          >精选题目</el-button
        >
        <el-button
          :type="formInline.range === 'user' ? 'primary' : ''"
          value="user"
          @click="formInline.range = 'user'"
          >我的题目</el-button
        >
      </el-button-group>
    </el-form-item>
    <div class="row">
      <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
        编号
      </div>
      <div class="col" :style="{ height: '42px', lineHeight: '42px' }">
        名称
      </div>
      <div
        :style="{
          width: '50px',
          padding: 0,
          height: '42px',
          lineHeight: '42px',
        }"
      ></div>
      <div
        :style="{
          width: '90px',
          padding: 0,
          height: '42px',
          lineHeight: '42px',
        }"
      >
        添加
      </div>
    </div>
    <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
    <div class="mydata">
      <el-scrollbar>
        <div
          class="row list"
          v-for="v in getquestion"
          :key="v.ID"
          :style="{ marginTop: '6px', marginBottom: '6px' }"
        >
          <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
            {{ v.ID }}
          </div>
          <div
            class="col text-truncate"
            :style="{ height: '42px', lineHeight: '42px' }"
          >
            {{ v.name }}
            <span :style="{ fontSize: '12px', color: '#888' }">{{
              v.goldremarks
            }}</span>
          </div>
          <!-- <el-link :href="`https://oj.hterobot.com/#/question/${v.ID}`" target="_blank" class="router-link-q">
                        预览
                    </el-link> -->
          <div
            class="text-center"
            :style="{
              width: '100px',
              padding: 0,
              height: '42px',
              lineHeight: '42px',
            }"
          >
            <span
              class="cu"
              :style="{
                width: '24px',
                height: '24px',
                background: 'var(--color-cheng)',
                borderRadius: '2px',
                display: 'inline-block',
                lineHeight: '24px',
              }"
              @click="addclick(v, formInline.range === 'match' ? true : false)"
            >
              <el-icon
                color="#fff"
                size="18px"
                :style="{ transform: 'translateY(3px)' }"
              >
                <Plus />
              </el-icon>
            </span>
          </div>
          <div class="col-12" :style="{ paddingLeft: '88px' }">
            <el-button
              type="primary"
              plain
              size="small"
              v-for="(vo, keys) in v.questionlabel"
              v-text="getlabel.find((e) => e.ID === vo.labelid)?.name"
              :key="`1-${keys}`"
            >
            </el-button>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <!-- <div class="row">
            <div class="col text-right"> -->
    <el-pagination
      class="pager"
      :page-size="limit"
      :total="getquestioncount"
      @current-change="currentchange"
      layout="total,prev, pager, next"
      :current-page="Math.floor(Number(formInline._offset) / limit) + 1"
    ></el-pagination>
    <!-- </div>
        </div> -->
  </el-form>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import { debounce, flatten } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import { Iobj } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { findpid } from "../../../util/code";
import { showCF } from "../../../util/data";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);
const limit = 13;

const store = useStore(Storekey);
const getuser = computed(() => {
  return store.state.user;
});

const teamId = computed(() => {
  return Number(getuser.value?.teamid);
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});
const showRemotejudge = computed(() => {
  return getteam.value.some((c) => c?.other?.showRemotejudge);
});
const vip = computed(() => {
  return getuser.value?.uservip?.find((c) => c.viplistid === 1);
});
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const getquestion = computed(() => {
  return store.state.question?.rows || [];
});

const p = defineProps<{
  addclick: Function;
  _include?: { [key in keyof Studycodemodel.Iquestion]: any };
  index?: keyof Studycodemodel.Imatchquestion;
  teamid?: number | number[];
  isAdmin?: boolean;
}>();

const formInline = reactive<Iobj<Studycodemodel.Iquestion>>({
  teamid: [],
  name: "",
  label: "",
  _offset: 0,
  range: p.isAdmin ? undefined : "public",
});

watch(formInline, () => {
  debouncet1.value();
});

const getquestioncount = computed(() => {
  return store.state.question?.count || 0;
});

function currentchange(r: number) {
  formInline._offset = (r - 1) * limit;
  debouncet1.value();
}

const loading = ref(false);

const debouncet1 = ref(debouncet());
function debouncet() {
  return debounce(async () => {
    const { name, teamid, _offset } = formInline;
    const obj: Iobj<Studycodemodel.Iquestion> = {
      _order: "ID",
      _offset,
      _limit: limit,
      testcases: true,
    };
    let _like: [keyof Studycodemodel.Iquestion, any];
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    let t;
    if (formInline.range == "team") {
      t = teamid.length ? teamid : getteam.value?.map((v) => v.ID);
      obj.teamid = t;
      if (p.teamid) {
        obj.teamid = p.teamid;
      }
    } else if (formInline.range == "user") {
      obj.userid = [store.state.user?.ID];
    } else {
      obj.range = formInline.range;
    }
    if (setlabel.value && setlabel.value.length) {
      const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
      const questionlabel = flatten(
        findpid(data ? data : [], setlabel.value[setlabel.value.length - 1])
      ).map((e) => e.ID);
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = [
        "labelid",
        questionlabel.concat(setlabel.value[setlabel.value.length - 1]),
      ];
    }
    if (p._include) {
      Object.assign(obj, {
        _include: {
          ...(obj._include || {}),
          ...p._include,
        },
      });
    }
    loading.value = true;
    await store.dispatch("actionquestion", obj);
    loading.value = false;
  }, 300);
}
const grouplabel = computed(() => {
  const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
  return findpid(data ? data : []);
});

const setlabel = ref<number[]>([]);

watch(
  () => setlabel.value,
  () => {
    debouncet1.value();
  }
);

onMounted(() => {
  debouncet1.value();
});
</script>

<style scoped>
.container-fluid {
  padding: 0;
  height: 856px;
}

.mydata {
  height: 640px;
  overflow-y: auto;
  overflow-x: hidden;
}

.input {
  display: inline-block;
  width: 45%;
}

.col-center div {
  width: 90px;
}

.icon-class-var {
  display: none;
}

.list {
  padding-bottom: 6px;
  width: 100%;
}

.list:hover {
  color: var(--color-cheng);
  background-color: #f8f8f8;
}

.list:hover .icon-class-var {
  display: inline-block;
}

.row {
  transition: all 0.4s;
}

.pager {
  float: right;
  margin-top: 5px;
}
</style>

<style>
.router-link-q {
  width: 50px;
  padding: 0;
  height: "42px";
  line-height: 42px;
  display: block;
  color: #333;
  text-align: center;
}

.router-link-q:hover {
  color: var(--color-cheng);
}
</style>
